<?php

namespace app\admin\controller\sales;

//use app\admin\controller\Storehouse;
use app\common\controller\Backend;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\data\Voucher;
use app\common\model\sales\SalesSlip;
use app\common\model\supplier\Supplier;
use app\web\controller\Wweixin;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use app\common\model\sales\Slip;
use app\common\model\sales\Retreat;
use app\common\model\sales\RetreatGoods;
use app\common\model\sales\ChangeGoods;
use app\common\model\sales\Change;
use app\common\model\sales\CheckoutGoods;
use app\common\model\Storehouse;
use app\common\model\sales\Goods;
use app\common\model\customer\Customer;
use think\Exception;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Checkout extends Backend
{
    
    /**
     * Checkout模型对象
     * @var \app\common\model\sales\Checkout
     */
    protected $model = null;
    protected $searchFields = 'customer.company,number,slip.number';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\sales\Checkout;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {


        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
//            dump(input());
//            exit;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $where['storehouse_id'] = 1;
            $total = $this->model
                    ->with(['customer','storehouse','slip'])
                    ->where($where)
//                    ->where(array('storehouse_id'=>1))
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['customer','storehouse','slip'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','number','collectiontime','address','explain','abstract','operator','company','status','tax','actual_cost']);
                $row->visible(['customer']);
				$row->getRelation('customer')->visible(['company']);
                $row->visible(['slip']);
                $row->getRelation('slip')->visible(['number']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $status = $this->model->checkout_status();
            foreach ($list as $k => $v){
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $status[$v['status']];
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add(){
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
        $sid = input('slip_id/d',0);
        $slip = new Slip;
        $row = $slip->find($sid);

        if(!$row){
            $this->error('没有对应销售单');
        }

        $customer = new Customer;
        $crow =  $customer->find($row['customer_id']);

        if ($this->request->isAjax()) {
            $params = input();
            if(!isset($params['row'])){
                $this->error('没有出库的商品');
            }
            $gdata = $params['row'];
            $sales_slip_id = $sid;
            $srow = $row;

            $num = Db::name('sales_checkout')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();


            $allfare = input('allfare/d');
            $discount = input('discount');
            $discount_explain = input('discount_explain');
            $actual_cost = input('actual_cost');
            if(empty($actual_cost)){
                $this->error('费用计算失败');
            }
            $checkout_num = 0;
            $goodsprice = 0;
            foreach ($gdata as $v){
                $checkout_num+=$v['goods_num'];
                $goodsprice+=$v['sfhj'];
                if(empty($v['sfhj']) || $v['sfhj'] == 0.00){
                    if($v['sale_price'] >0){
                        $this->error('费用异常');
                    }
//                    $this->error('费用异常');
                }
            }

//            if($goodsprice+$allfare != $actual_cost){
            if(!compare($goodsprice+$allfare,$actual_cost)){
                $this->error('计算费用异常');
            }


            //添加出库单
            $data = array(
//                'createtime'=>strtotime(input('createtime')),
                'number'=>'XK-T-'.date('Y-m-d').'-'.getnumber($num),
                'customer_id'=>$row['customer_id'],
                'storehouse_id'=>$row['storehouse_id'],
                'collectiontime'=>strtotime(input('deliverytime')),
                'address'=>empty($srow['address'])?$crow['address']:$srow['address'],
                'contacts'=>empty($srow['contacts'])?$crow['contacts']:$srow['contacts'],
                'mobile'=>empty($srow['mobile'])?$crow['mobile']:$srow['mobile'],
                'explain'=>input('explain'),
//                'abstract'=>input('abstract'),
                'sales_slip_id'=>$sid,
                'tax'=>$srow['tax'],
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'allfare'=>$allfare,
                'discount'=>$discount,
                'discount_explain'=>$discount_explain,
                'actual_cost'=>$actual_cost,
                'checkout_num'=>$checkout_num,
            );

            Db::startTrans();
            try {
                $this->model->save($data);
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$row['storehouse_id'],
                    'bill_id'=>$this->model->id,
                    'type'=>7,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                $cids = [];
                //添加 入库商品信息
                //数据对比
                foreach ($gdata as $v) {
                    $cids[] = $v['goods_id'];
                    $goods = new Goods();
                    $ginfo = $goods->where(array('sales_slip_id' => $sales_slip_id, 'goods_id' => $v['goods_id']))->find();

                    $GoodsHouseStock = new GoodsHouseStock;
                    $stock = $GoodsHouseStock->getstock($ginfo['goods_id'],$ginfo['storehouse_id']);
//                    $xstock = $GoodsHouseStock->getfictstock($ginfo['goods_id'],$ginfo['storehouse_id']);

                    if($stock-$v['goods_num']<0){
                        throw new Exception('商品' . $v['goods_id'] . '账面库存不足');
                    }
//                    if($xstock<0){
//                        throw new Exception('商品' . $v['goods_id'] . '虚拟库存不足');
//                    }

                    //剩余出库数量 = 销售数量-已出库数量-已转换数量
                    $EnterGoods = new CheckoutGoods;
                    $egoodcont = $EnterGoods->where(array('sales_slip_id' => $sales_slip_id, 'goods_id' => $v['goods_id'],'status'=>1))->sum('goods_num');
                    $change_num = Db::name('factory_sales_goods')->where(array('sales_slip_id'=>$sales_slip_id,'goods_id'=>$v['goods_id'],'status'=>array('>',0)))->sum('goods_num');


                    if ($v['goods_num'] > $ginfo['goods_num'] - $egoodcont-$change_num) {
                        throw new Exception('商品' . $v['goods_id'] . '数量超过销售数量,目前出库' . $egoodcont);
                    } else {//粗糙记录商品状态
                        $Goods = new Goods;
                        $Goods->save(array('status'=>2),array('sales_slip_id'=>$sales_slip_id,'goods_id' => $v['goods_id']));
                    }
                    $gods = new \app\common\model\goods\Goods();
                    $costPrice = $gods->getcost($v['goods_id'],$row['storehouse_id']);
                    //存储记录
                    $cgdata[] = array(
                        'sales_slip_id' => $sales_slip_id,
                        'costPrice' => $costPrice,
                        'storehouse_id' => $row['storehouse_id'],
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sfhj' => $v['sfhj'],
                        'sale_price' => $ginfo['sale_price'],
                        'tax' => $ginfo['tax'],
                        'remark' => $v['remark'],
                        'ht_price' => $v['ht_price'],
                        'sales_checkout_id' => $this->model->id,
                        'customer_id' => $row['customer_id'],
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'createtime'=>time(),
                    );

                }
                $CheckoutGoods = new CheckoutGoods;
                $CheckoutGoods->saveAll($cgdata);
                //判断销售单是否完成
                $gnum = Db::name('sales_goods')->where(array('sales_slip_id' => $sales_slip_id,'status'=>array('>',0)))->sum('goods_num');
                $goods = new CheckoutGoods();
                //出库数量
                $succnum = $goods->where(array('sales_slip_id' => $sales_slip_id,'status'=>array('>=',1)))->sum('goods_num');
                //转换数量
                $allchange = Db::name('factory_sales_goods')->where(array('sales_slip_id'=>$sales_slip_id,'status'=>array('>',0)))->sum('goods_num');


                if ($gnum == $succnum+$allchange) {
                        $Slip = new Slip;
                        $Slip->save(array('status' => 4), array('id' => $sales_slip_id));
                } else {
                        $Slip = new Slip;
                        $Slip->save(array('status' => 3), array('id' => $sales_slip_id));
                }

                $hrow = Db::name('storehouse')->where(array('id'=>$row['storehouse_id']))->find();
                if($hrow['checkout_status'] == 1){
                    $this->skipstep($this->model->id,2);
                }

                $wx = new Wweixin;
                $wx->senmsg(7);

                Db::commit();
                return array(
                    'code' => 1,
                    'msg' => '添加成功'
                );
            }catch (\Exception $e) {
//                dump($e);
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }


        $list = Db::name('sales_goods')
            ->field('s.goods_id,s.goods_num,s.sale_price,s.tax,s.remark,title,place_origin,number,unit,specs,ht_price,sfhj')
            ->where(array('s.sales_slip_id'=>$sid,'s.status'=>array('in',[1,2])))
            ->alias('s')
            ->join('goods g','s.goods_id = g.id')
            ->select();

            if(session('admin')['storehouse_id'] >0){
                $hrow = Db::name('storehouse')->where(array('id'=>session('admin')['storehouse_id']))->find();
            }else{
                $hrow = Db::name('storehouse')->where(array('is_default'=>1))->find();
            }
        $numbers = [];
        foreach ($list as $k => $v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$row['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);
            $checkoutgoods = new CheckoutGoods();
            //出库的数量
            $cnum = $checkoutgoods->where(array('goods_id'=>$v['goods_id'],'sales_slip_id'=>$row['id'],'status'=>array('>',0)))->sum('goods_num');

            $list[$k]['cnum'] = $cnum;
           //转换的数量
            $change_num = Db::name('factory_sales_goods')->where(array('sales_slip_id'=>$row['id'],'goods_id'=>$v['goods_id'],'status'=>array('>',0)))->sum('goods_num');
            $list[$k]['change_num'] = $change_num;

            if($change_num+$cnum>0){
                $list[$k]['sfhj'] = $v['sale_price']*($v['goods_num']-$cnum-$change_num)*(1+$v['tax']/100);
            }
            $numbers[] = $v['number'];
        }
        $url =  config('site.syncurl').'/api/sync/batchprice';

        $json = curl_post($url,array(
            'numbers'=>implode(',',$numbers),
            'code'=>$hrow['code'],
            'appkey'=>config('site.appkey'),
        ));
        $json = json_decode($json,true);
        if($json['code'] == 1){
            foreach ($list as &$v){
                foreach ($json['data'] as $val){
                    if($v['number'] == $val['spec_num']){
                        $v['jxs_price'] = $val['jxs_price'];
                    }
                }
                if(!isset($v['jxs_price'])){
                    $v['jxs_price'] = 0;
                }
            }
        }else{
            foreach ($list as &$v){
                $v['jxs_price'] = 0;
            }
        }

        $this->assign('crow',$crow);
        $this->assign('sid',$sid);
        $this->assign('row',$row);
        $this->assign('list',$list);
        $this->assign('nickname',session('admin')['nickname']);
        $this->assign('gname',$group['name']);
        return $this->view->fetch();
    }
    public function detail($ids = null){
        if ($this->request->isAjax()) {
            $status = input('status/d',0);
            if(!$status){
                $this->error('非法操作');
            }
            $row = $this->model->find($ids);
            Db::startTrans();
            try {
                $res = $this->model->save(array('status' => $status), array('id' => $ids));
                if ($res) {
                    //审核之后生成财务单据
                    if($status == 2){
                        $type = 1;
                        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                        $custrow = Customer::find($row['customer_id']);

                        $srow = Db::name('sales_slip')->where(array('id'=>$row['sales_slip_id']))->find();
                        if(empty($srow)){
                            throw new Exception('单据异常');
                        }
                        $ress = Db::name('analysis')->insert(array(
                            'is_income'=>1,
                            'source'=>7,
                            'cost'=>$row['actual_cost'],
//                            'admin_id'=>session('admin')['id'],
//                            'group_id'=>$group['group_id'],
//                            'company'=>$group['name'],
                            'admin_id'=>$srow['admin_id'],
                            'group_id'=>$srow['group_id'],
                            'company'=>$srow['company'],
                            'operator'=>$srow['operator'],

                            'source_id' => $row['id'],
                            'obj_id' => $row['customer_id'],
//                            'operator'=>session('admin')['nickname'],
                            'controller'=>'sales/checkout',
                            'settle_name'=>$custrow['company'],
                            'number'=>$row['number'],
                            'createtime'=>time(),
                            'storehouse_id' => $row['storehouse_id'],
                            'explain'=>$row['explain'],//摘要
                        ));
                        if (!$ress) {
                            throw new Exception('数据异常');
                        }
                    }
                    if($status == 5){
                        $type = 2;
                        $checkoutgoods = new CheckoutGoods();
                        $checkoutgoods->save(array('status'=>0),array('sales_checkout_id'=>$ids));

                        $goodsids = Db::name('sales_checkout_goods')->where(array('sales_checkout_id'=>$ids))->column('goods_id');
                        Db::name('sales_goods')->where(array('sales_slip_id'=>$row['sales_slip_id'],'goods_id'=>array('in',$goodsids)))->update(array('status'=>1));

//                        $srow = Slip::where(array('id'=>$row['sales_slip_id']))->find();
//                        if($srow['status'] == 4){//退回状态
//                            Slip::where(array('id'=>$row['sales_slip_id']))->update(array('status'=>3));
//                        }
                        $count = Db::name('sales_checkout')->where(array('status'=>array('<',4),'sales_slip_id'=>$row['sales_slip_id']))->count();
                        if($count >0){
                            $slip = new Slip();
                            $slip->save(array('status'=>3),array('id'=>$row['sales_slip_id']));
                        }else{
                            $slip = new Slip();
                            $slip->save(array('status'=>2),array('id'=>$row['sales_slip_id']));
                        }


                    }
                    Db::name('examine_log')->insert(array(
                        'admin_id'=>session('admin')['id'],
                        'type'=>$type,
                        'createtime'=>time(),
                        'controller'=>'sales/checkout',
                        'source_id'=>$ids,
                        'source'=>7,
                        'remark'=>'销售出库单',
                        'number'=>isset($row['number'])?$row['number']:'',
                    ));
                    Db::commit();
                    return array(
                        'code' => 1,
                        'msg' => '成功'
                    );
                }
                throw new Exception('错误异常');
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
//        $row = $this->model->find($ids);
        $row = Db::name('sales_checkout')
            ->where(array('sc.id'=>$ids))
            ->field('sc.*,c.company as ccompany,s.name')
            ->alias('sc')
            ->join('customer c','sc.customer_id = c.id')
            ->join('storehouse s','sc.storehouse_id = s.id')
            ->find();

        $list = Db::name('sales_checkout_goods')
            ->field('g.id,goods_id,storehouse_id,number,title,place_origin,specs,goods_num,unit,sale_price,ht_price,tax,remark,costPrice,sfhj')
            ->alias('g')
            ->where(array('g.sales_checkout_id'=>$ids))
            ->join('goods go','g.goods_id = go.id')
            ->select();

        foreach ($list as $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['buy_price'] = round($v['goods_num']*$v['sale_price'],2);
            $list[$k]['tax_all'] = round($v['sale_price']*$v['tax']*$v['goods_num']/100,2);
            if($v['sfhj'] == 0.00){
                $list[$k]['sfhj'] = round(($v['sale_price']*$v['goods_num']*(1+$v['tax']/100)),2);
            }
        }
        $this->assign('is_finance',input('is_finance/d',0));
        $this->assign('snick',isset($srow['nickname'])?$srow['nickname']:'');
        $this->assign('hname',isset($hrow['name'])?$hrow['name']:'');
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    protected function  skipstep($ids,$status = 2){
        $row = Db::name('sales_checkout')->where(array('id'=>$ids))->find();
        //自动过审
        Db::name('sales_checkout')->where(array('id'=>$ids))->update(array('status' => $status));
        if($status == 2){
            $type = 1;
            $custrow = Customer::find($row['customer_id']);

            $srow = Db::name('sales_slip')->where(array('id'=>$row['sales_slip_id']))->find();
            if(empty($srow)){
                throw new Exception('单据异常');
            }
            $ress = Db::name('analysis')->insert(array(
                'is_income'=>1,
                'source'=>7,
                'cost'=>$row['actual_cost'],
                'admin_id'=>$srow['admin_id'],
                'group_id'=>$srow['group_id'],
                'company'=>$srow['company'],
                'operator'=>$srow['operator'],
                'source_id' => $row['id'],
                'obj_id' => $row['customer_id'],
                'controller'=>'sales/checkout',
                'settle_name'=>$custrow['company'],
                'number'=>$row['number'],
                'createtime'=>time(),
                'storehouse_id' => $row['storehouse_id'],
                'explain'=>$row['explain'],//摘要
            ));
            if (!$ress) {
                throw new Exception('数据异常');
            }
        }
        Db::name('examine_log')->insert(array(
            'admin_id'=>session('admin')['id'],
            'type'=>$type,
            'createtime'=>time(),
            'controller'=>'sales/checkout',
            'source_id'=>$ids,
            'source'=>7,
            'remark'=>'销售出库单',
            'number'=>isset($row['number'])?$row['number']:'',
        ));

        //自动 发货
        $Slip = new Slip;
        $ress = $Slip->checkstatus($row['sales_slip_id']);
        if(!$ress){
            throw new Exception('异常错误');
        }

        $plist = Db::name('sales_checkout_goods')->where(array('sales_checkout_id'=>$ids))->select();
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();


        foreach ($plist as $k=>$v){
            //修改销售单商品状态
            $sliprow = Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->find();
            $change_num = Db::name('factory_sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id'],'status'=>array('>',0)))->sum('goods_num');
            if($sliprow['goods_num'] == $v['goods_num']+$change_num){ //出库完成
                Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>3));
            }else{
                $num = Db::name('sales_checkout_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id'],'status'=>2))->sum('goods_num');//已经出库的商品数量
                if($num+$v['goods_num']+$change_num == $sliprow['goods_num']){
                    Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>3));
                }
            }
            Db::name('sales_checkout_goods')->where(array('id'=>$v['id']))->update(array('status'=>2));

            $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
            if($hgood['stock'] == 0){
                throw new Exception('库存为0');
            }

            if($hgood['stock'] == $v['goods_num']){
                $balance = 0;
            }else{
                $balance = $hgood['balance']-($hgood['balance']/$hgood['stock'])*$v['goods_num'];
            }

            Db::name('goods_stock_log')->insert(array(
                'goods_id'=>$v['goods_id'],
                'createtime'=>time(),
                'number'=>$row['number'],
                'type'=>'销售出库单',
                'source'=>7,
                'type_id'=>$row['id'],
                'out_num'=>$v['goods_num'],
                'before_num'=>$hgood['stock'],
                'now_num'=>$hgood['stock']-$v['goods_num'],
                'storehouse_id'=>$row['storehouse_id'],
                'controller'=>'sales/checkout',
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                'bill_cost'=>($hgood['balance']/$hgood['stock'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                'balance'=>$balance, //记录的金额当前库存总额
            ));
            //减少库存

            $GoodsHouseStock = new GoodsHouseStock;
            $rr = $GoodsHouseStock->reducestock($v['goods_id'],$row['storehouse_id'],$v['goods_num']);
            if(!$rr){
                throw new Exception('库存异常');
            }
        }
        $data = array(
            'image'=>'',
            'remark'=>'自动发货',
            'type'=>7,
            'source_id'=>$ids,
        );
        $Voucher = new Voucher;
        $Voucher->save($data);

        Db::name('sales_checkout')->where(array('id'=>$ids))->update(array('status'=>4));

    }
//    public function delivery($ids = null){
//        $status = input('status/d',0);
//        if(!$status){
//            $this->error('非法操作');
//        }
//        $res = $this->model->save(array('status' => $status), array('id' => $ids));
//        if($res){
//            $this->success('发货成功');
//        }else{
//            $this->error('发货失败');
//        }
//    }
//    public function examine($ids = null){
//        $status = input('status/d',0);
//        if(!$status){
//            $this->error('非法操作');
//        }
//        $row = $this->model->find($ids);
//        Db::startTrans();
//        try {
//            $res = $this->model->save(array('status' => $status), array('id' => $ids));
//            if ($res) {
//                //审核之后生成财务单据
//                if($status == 2){
//                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
//                    $custrow = Customer::find($row['customer_id']);
//
//                    $ress = Db::name('analysis')->insert(array(
//                        'is_income'=>1,
//                        'source'=>7,
//                        'cost'=>$row['actual_cost'],
//                        'admin_id'=>session('admin')['id'],
//                        'group_id'=>$group['group_id'],
//                        'company'=>$group['name'],
//                        'source_id' => $row['id'],
//                        'obj_id' => $row['customer_id'],
//                        'operator'=>session('admin')['nickname'],
//                        'controller'=>'sales/checkout',
//                        'settle_name'=>$custrow['company'],
//                        'number'=>$row['number'],
//                        'createtime'=>time(),
//                        'storehouse_id' => $row['storehouse_id'],
//                        'explain'=>$row['explain'],//摘要
//                    ));
//                    if (!$ress) {
//                        throw new Exception('数据异常');
//                    }
//                    $type = 1;
//                }
////                if ($status == 3) {//确定出库
////                    $Slip = new Slip;
////                    $ress = $Slip->checkstatus($row['sales_slip_id']);
////                    if(!$ress){
////                        throw new Exception('异常错误');
////                    }
////                }
//                if($status == 5){
//                    $type =2;
//                    $checkoutgoods = new CheckoutGoods();
//                    $checkoutgoods->save(array('status'=>0),array('sales_checkout_id'=>$ids));
//
//                    $srow = Slip::where(array('id'=>$row['sales_slip_id']))->find();
//                    if($srow['status'] == 4){//退回状态
//                        Slip::where(array('id'=>$row['sales_slip_id']))->update(array('status'=>3));
//                    }
//                }
//                Db::name('examine_log')->insert(array(
//                    'admin_id'=>session('admin')['id'],
//                    'type'=>$type,
//                    'createtime'=>time(),
//                    'controller'=>'sales/checkout',
//                    'source_id'=>$ids,
//                    'source'=>7,
//                    'remark'=>'销售出库单',
//                    'number'=>isset($row['number'])?$row['number']:'',
//                ));
//                Db::commit();
//                return array(
//                    'code' => 1,
//                    'msg' => '成功'
//                );
//            }
//            throw new Exception('错误异常');
//        }catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
//    }
    public function examine2($ids = null){
        $row  = $this->model->find($ids);
        if(empty($row)){
            $this->error('暂无数据');
        }
        if ($this->request->isAjax()) {
            $params = input('row/a');
            if(empty($params['thumb']) && empty($params['remark'])){
                $this->error('至少选择一项内容输入');
            }
            $data = array(
                'image'=>$params['thumb'],
                'remark'=>$params['remark'],
                'type'=>7,
                'source_id'=>$ids,
            );
            //减少库存
            Db::startTrans();
            try {
                $Slip = new Slip;
                $ress = $Slip->checkstatus($row['sales_slip_id']);
                if(!$ress){
                    throw new Exception('异常错误');
                }

                $plist = Db::name('sales_checkout_goods')->where(array('sales_checkout_id'=>$ids))->select();
                $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();


                foreach ($plist as $k=>$v){
                    //检测出库单里是否有没分摊的数据
                    $share_num = Db::name('purchase_enter_goods')->where(array('goods_id'=>$v['goods_id'],'status'=>array('>',0),'is_share'=>0))->count();
                    if($share_num>0){
                        throw new Exception($v['id'].'存在未处理完成的入库');
                    }


                    //修改销售单商品状态
                    $sliprow = Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->find();
                   $change_num = Db::name('factory_sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id'],'status'=>array('>',0)))->sum('goods_num');
                    if($sliprow['goods_num'] == $v['goods_num']+$change_num){ //出库完成
                        Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>3));
                    }else{
                        $num = Db::name('sales_checkout_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id'],'status'=>2))->sum('goods_num');//已经出库的商品数量
                        if($num+$v['goods_num']+$change_num == $sliprow['goods_num']){
                            Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>3));
                        }
                    }
                    Db::name('sales_checkout_goods')->where(array('id'=>$v['id']))->update(array('status'=>2));

                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                    if($hgood['stock'] == 0){
                        throw new Exception('库存为0');
                    }

                    if($hgood['stock'] == $v['goods_num']){
                        $balance = 0;
                    }else{
                        $balance = $hgood['balance']-($hgood['balance']/$hgood['stock'])*$v['goods_num'];
                    }

                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'销售出库单',
                        'source'=>7,
                        'type_id'=>$row['id'],
//                       'enter_num'=>$v['goods_num'],
                        'out_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock'],
                        'now_num'=>$hgood['stock']-$v['goods_num'],
                        'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                        'controller'=>'sales/checkout',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                        'bill_cost'=>($hgood['balance']/$hgood['stock'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                        'balance'=>$balance, //记录的金额当前库存总额
                    ));
                    //减少库存

                    $GoodsHouseStock = new GoodsHouseStock;
                    $rr = $GoodsHouseStock->reducestock($v['goods_id'],$row['storehouse_id'],$v['goods_num']);
                    if(!$rr){
                        throw new Exception('库存异常');
                    }
                }
                $Voucher = new Voucher;
                $Voucher->save($data);

                $res = $this->model->save(array('status'=>3),array('id'=>$ids));
                if($res){
                    Db::commit();
                    return array(
                        'code'=>1,
                        'msg'=>'发货成功',
                    );
                }else{
                    throw new Exception('状态异常');
                }
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            exit;
        }

        return $this->view->fetch();
    }
    public function examine3($ids = null){
        $row  = $this->model->find($ids);
        if(empty($row)){
            $this->error('暂无数据');
        }
        if ($this->request->isAjax()) {
            $params = input('row/a');
            if(empty($params['thumb']) && empty($params['remark'])){
                $this->error('至少选择一项内容输入');
            }
            $data = array(
                'image'=>$params['thumb'],
                'remark'=>$params['remark'],
                'type'=>7,
                'is_go'=>2,
                'source_id'=>$ids,
            );
            Db::startTrans();
            try {
                $Voucher = new Voucher;
                $Voucher->save($data);

                $res = $this->model->save(array('status'=>4),array('id'=>$ids));


                $slip = new Slip();
                $srow = $slip->find($row['sales_slip_id']);
                if($srow['status'] == 4){  //如果在等待确认了 就判断是否完成
                    $all_num = Db::name('sales_checkout')->where(array('sales_slip_id'=>$row['sales_slip_id'],'status'=>array('<',5)))->count();
                    $suc_num =Db::name('sales_checkout')->where(array('sales_slip_id'=>$row['sales_slip_id'],'status'=>4))->count();
//                    $suc_num =Db::name('sales_checkout')->where(array('sales_slip_id'=>$row['sales_slip_id'],'status'=>array('in',[4,6])))->count();

                    if($all_num == $suc_num){
                        $slip = new Slip();
                        $slip->save(array('status'=>5),array('id'=>$row['sales_slip_id']));
                        Db::name('sales_goods')->where(array('sales_slip_id'=>$row['sales_slip_id'],'status'=>array('<',5)))->update(array('status'=>4));
                    }
                }
//
                if($res){
                    Db::commit();
                    return array(
                        'code'=>1,
                        'msg'=>'设置成功',
                    );
                }
                throw new Exception('状态异常');
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            exit;
        }

        return $this->view->fetch('examine2');
    }
    public function retreat($ids){

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

        $row = $this->model->find($ids);

        if ($this->request->isAjax()) {

            $collectiontime = strtotime(input('collectiontime'));
//            $createtime = strtotime(input('createtime'));

            $explain = input('explain');
            $declare = input('declare');
//            $abstract = input('abstract');
            $allfare = input('allfare');
            $discount = input('discount');
            $discount_explain = input('discount_explain');
            $actual_cost = input('actual_cost');

            if(empty($actual_cost)){
                $this->error('费用计算错误');
            }

            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            $sdata = $params['row'];

            $retreat_num = 0;
            $allprice = 0;
            foreach ($sdata as $k=> $v){
                $RetreatGoods = new RetreatGoods();
                $where = array(
                    'goods_id' => $v['goods_id'],
                    'sales_checkout_id' => $ids,
                    'sales_slip_id' => $row['sales_slip_id'],
                );
                $rnum = $RetreatGoods->where(array(
                    'goods_id' => $v['goods_id'],
                    'sales_checkout_id' => $ids,
                    'sales_slip_id' => $row['sales_slip_id'],
                    'status'=>array('in',[1,2])
                ))->sum('goods_num');//已经退货数量
                $CheckoutGoods = new CheckoutGoods;
                $gnum = $CheckoutGoods->where($where)->sum('goods_num');

                if($v['goods_num']+$rnum >$gnum){
                    $this->error('商品'.$v['goods_id'].'退货超量,已经退货'.$rnum);
                }
                $retreat_num +=$v['goods_num'];
                $allprice+=$v['sfhj'];
            }
//            if($allprice+$allfare != $actual_cost){
            if(!compare($allprice+$allfare,$actual_cost)){
                $this->error('计算费用失败');
            }
            $num = Db::name('sales_retreat')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $saledata = array(
                'number'=>'XT-T-'.date('Y-m-d').'-'.getnumber($num),
                'collectiontime'=>$collectiontime,
                'customer_id'=>$row['customer_id'],
                'storehouse_id'=>$row['storehouse_id'],
                'explain'=>$explain,
//                'abstract'=>$abstract,
                'tax'=>$row['tax'],
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'sales_slip_id' => $row['sales_slip_id'],
                'operator'=>session('admin')['nickname'],
                'sales_checkout_id' => $ids,
//                'status' => 2,
                'allfare' => $allfare,
                'discount' => $discount,
                'discount_explain' => $discount_explain,
                'actual_cost' => $actual_cost,
                'declare' => $declare,
                'retreat_num' => $retreat_num,
            );
            Db::startTrans();
            try {

                $Retreat = new Retreat;
                $Retreat->save($saledata);
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$row['storehouse_id'],
                    'bill_id'=>$Retreat->id,
                    'type'=>9,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                $gdata = [];

                foreach ($sdata as $k => $v) {
                    $info = CheckoutGoods::where(array('sales_checkout_id'=>$ids,'goods_id'=>$v['goods_id']))->find();
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'ht_price' => $v['ht_price'],
                        'tax' => $v['tax'],
                        'sfhj' => $v['sfhj'],
                        'remark' => $v['remark'],
                        'sales_checkout_id' => $ids,
                        'sales_slip_id' => $row['sales_slip_id'],
                        'sales_retreat_id' => $Retreat->id,
                        'storehouse_id'=>$row['storehouse_id'],
                        'customer_id' => $row['customer_id'],
                        'costPrice' => $info['costPrice'],
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                    );
                }
                $RetreatGoods = new RetreatGoods();
                $RetreatGoods->saveAll($gdata);
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'添加成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            exit;
        }
        $glist = Db::name('sales_checkout_goods')
            ->field('g.id,storehouse_id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,ht_price,sfhj')
            ->alias('sg')
            ->where(array('sales_checkout_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();

        foreach ($glist as $k => $v){
            $RetreatGoods = new RetreatGoods();
            $ChangeGoods = new ChangeGoods();
            $where = array(
                'goods_id' => $v['id'],
                'sales_checkout_id' => $ids,
                'sales_slip_id' => $row['sales_slip_id'],
                'status'=>1,
            );
            $rnum = $RetreatGoods->where($where)->sum('goods_num');//已经退货数量
            $cnum = $ChangeGoods->where($where)->sum('goods_num');//已经退货数量
            $glist[$k]['rnum'] =$rnum+$cnum;

            $GoodsHouseStock = new GoodsHouseStock;
            $glist[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['id'],$v['storehouse_id']);
            $glist[$k]['stock'] = $GoodsHouseStock->getstock($v['id'],$v['storehouse_id']);
            if(!empty($rnum) || !empty($cnum)){
                $glist[$k]['count'] = round($v['sale_price']*($v['goods_num']-$rnum-$cnum)*(1+$v['tax']/100),2);
            }else{
                if($glist[$k]['sfhj'] == 0.00){
                    $glist[$k]['count'] = round($v['sale_price']*($v['goods_num']-$rnum-$cnum)*(1+$v['tax']/100),2);
                }else{
                    $glist[$k]['count'] = $v['sfhj'];
                }
            }

        }
        $srow = Slip::find($row['sales_slip_id']);


        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('glist',$glist);
        $this->assign('row',$row);
        $this->assign('srow',$srow);
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    public function change($ids){

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

        $row = $this->model->find($ids);

        if ($this->request->isAjax()) {

            $collectiontime = strtotime(input('collectiontime'));
//            $createtime = strtotime(input('createtime'));
            $declare = input('declare');
            $explain = input('explain');
            $allfare = input('allfare');
            $discount = input('discount');
            $discount_explain = input('discount_explain');
            $actual_cost = input('actual_cost');
//            $abstract = input('abstract');
            if(empty($actual_cost)){
                $this->error('费用计算错误');
            }
            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            if(!isset($params['crow'])){
                $this->error('未选择换货商品');
            }
            $sdata = $params['row'];
            //检测库存
            $cdata = $params['crow'];

            foreach ($sdata as $k=> $v){
                $ChangeGoods = new ChangeGoods();
                $where = array(
                    'sales_checkout_id' => $ids,
                    'sales_slip_id' => $row['sales_slip_id'],
                );
                $cnum = $ChangeGoods->where(array(
                    'sales_checkout_id' => $ids,
                    'sales_slip_id' => $row['sales_slip_id'],
                    'goods_type'=>1,
                    'status'=>array('>',0),
                ))->sum('goods_num');//已经换货数量

                //退货数量
                $RetreatGoods = new RetreatGoods();
                $tnum = $RetreatGoods->where(array('status'=>array('>',0),'sales_checkout_id'=>$ids,'goods_id'=>$v['goods_id']))->sum('goods_num');

                $CheckoutGoods = new CheckoutGoods;
                $gnum = $CheckoutGoods->where($where)->sum('goods_num');

                if($v['goods_num']+$cnum+$tnum >$gnum){
                    $this->error('商品'.$v['goods_id'].'换货超量,已经换货'.($cnum+$tnum));
                }
            }
            $num = Db::name('sales_change')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $saledata = array(
                'number'=>'XT-T-'.date('Y-m-d').'-'.getnumber($num),
                'collectiontime'=>$collectiontime,
                'customer_id'=>$row['customer_id'],
                'storehouse_id'=>$row['storehouse_id'],
                'explain'=>$explain,
//                'abstract'=>$abstract,
                'tax'=>$row['tax'],
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'sales_slip_id' => $row['sales_slip_id'],
                'operator'=>session('admin')['nickname'],
                'sales_checkout_id' => $ids,
                'allfare' => $allfare,
                'discount' => $discount,
                'discount_explain' => $discount_explain,
                'actual_cost' => $actual_cost,
                'declare' => $declare,
            );

            Db::startTrans();
            try {
                $Change = new Change();
                $Change->save($saledata);
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$row['storehouse_id'],
                    'bill_id'=>$Change->id,
                    'type'=>8,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                $gdata = [];
                //退货商品
                foreach ($sdata as $k => $v) {
                    $info = CheckoutGoods::where(array('sales_checkout_id'=>$ids,'goods_id'=>$v['goods_id']))->find();
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'ht_price' => $v['ht_price'],
                        'tax' => $v['tax'],
                        'remark' => $v['remark'],
                        'sfhj' => $v['sfhj'],
                        'sales_checkout_id' => $ids,
                        'sales_slip_id' => $row['sales_slip_id'],
                        'sales_change_id' => $Change->id,
                        'customer_id' => $row['customer_id'],
                        'costPrice' => $info['costPrice'],
                        'storehouse_id'=>$row['storehouse_id'],
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                    );
                }
                //换货商品
                foreach ($cdata as $v){
                    $Goods = new \app\common\model\goods\Goods();
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'ht_price' => $v['ht_price'],
                        'tax' => $v['tax'],
                        'sfhj' => $v['sfhj'],
                        'remark' => $v['remark'],
                        'sales_checkout_id' => $ids,
                        'sales_slip_id' => $row['sales_slip_id'],
                        'sales_change_id' => $Change->id,
                        'goods_type'=>2,
                        'customer_id' => $row['customer_id'],
                        'costPrice' => 0,
                        'storehouse_id'=>$row['storehouse_id'],
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                    );
                }
                $ChangeGoods = new ChangeGoods();
                $ChangeGoods->saveAll($gdata);
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'添加成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }


            exit;
        }
        $glist = Db::name('sales_checkout_goods')
            ->field('g.id,storehouse_id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,ht_price,sfhj')
            ->alias('sg')
            ->where(array('sales_checkout_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();

        foreach ($glist as $k=> $v){
            $RetreatGoods = new RetreatGoods();
            $changegoods = new ChangeGoods();
            $glist[$k]['tnum'] = $changegoods->where(array('status'=>array('>',0),'sales_checkout_id'=>$ids,'goods_id'=>$v['id'],'goods_type'=>1))->sum('goods_num');
            $glist[$k]['tnum'] += $RetreatGoods->where(array('status'=>array('>',0),'sales_checkout_id'=>$ids,'goods_id'=>$v['id']))->sum('goods_num');
            $GoodsHouseStock = new GoodsHouseStock;
            $glist[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['id'],$v['storehouse_id']);
            $glist[$k]['stock'] = $GoodsHouseStock->getstock($v['id'],$v['storehouse_id']);
            if($glist[$k]['tnum']>0){
                $glist[$k]['count'] = round(($v['goods_num']-$glist[$k]['tnum'])*$v['sale_price']*($v['tax']/100+1),2);
            }else{
                if($v['sfhj'] == 0.00){
                    $glist[$k]['count'] =round($v['goods_num']*$v['sale_price']*($v['tax']/100+1),2);
                }else{
                    $glist[$k]['count'] = $v['sfhj'];
                }
            }
        }

        $srow = Slip::find($row['sales_slip_id']);

        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('glist',$glist);
        $this->assign('row',$row);
        $this->assign('srow',$srow);
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    public function export(){
        $this->assign('statuslist',$this->model->checkout_status());
        return $this->view->fetch();
    }
    public function exportExcel(){
        $start_time = input('start_time');
        $end_time = input('end_time');
        $status = input('status/d',0);
        $customer_id = input('customer_id/d',0);
        $storehouse_id = input('storehouse_id/d',0);

        if($status>0){
           $where['status'] = $status;
        }
        $where = [];
        if($customer_id){
            $where['customer_id'] = $customer_id;
        }

        if(empty($start_time)){
            $start_time = 0;
        }
        $ccrow = [];
        if($customer_id){
            $ccrow = Customer::get($customer_id);
        }
        if($storehouse_id >0){
            $where['storehouse_id'] = $storehouse_id;
        }
        if(empty($end_time)){
            $end_time = time();
        }

        $where['createtime'] =  array('between time',[$start_time,$end_time]);

        $ids = [];

        $rows = $this->model->where($where)->select();

        foreach ($rows as $v){
            $ids[] = $v['id'];
        }
        $list = Db::name('sales_checkout_goods')
            ->field('cg.*,sc.*,h.name,g.title,sc.customer_id,g.specs,sfhj')
            ->alias('cg')
            ->where(array('sales_checkout_id'=>array('in',$ids)))
            ->join('sales_checkout sc','cg.sales_checkout_id = sc.id')
            ->join('storehouse h','cg.storehouse_id = h.id')
            ->join('goods g','cg.goods_id = g.id')
            ->select();

//        $gids = [];
//        foreach ($list as $v){
//            $gids[] = $v['id'];
//        }
        $retreatgoods = Db::name('sales_retreat_goods')
            ->alias('rg')
            ->join('sales_retreat s','rg.sales_retreat_id=s.id')
            ->where(array('s.sales_checkout_id'=>array('in',$ids)))
            ->select();
        $changegoods = Db::name('sales_change_goods')
            ->alias('rg')
            ->join('sales_change s','rg.sales_change_id=s.id')
            ->where(array('s.sales_checkout_id'=>array('in',$ids)))
            ->select();
        foreach ($list as $k=> $v){
            foreach ($retreatgoods as $val){
                if($v['goods_id'] == $val['goods_id']){
                    $list[$k]['goods_num'] -=$val['goods_num'];
                }
            }
            foreach ($changegoods as $val){
                if($v['goods_id'] == $val['goods_id']){
                    $list[$k]['goods_num'] -=$val['goods_num'];
                }
            }
        }
//        dump($retreatgoods);
//        dump($changegoods);

        //运费 优惠等
        $template_path = config('site.file_url').'/template/contact.xls';
        $spreadsheet = IOFactory::load($template_path);
        $worksheet = $spreadsheet->getActiveSheet();

        $len = count($list);
        $rows = $list;

        $allnum = 0;
        $allprice = 0;

        for ($i=0; $i < $len; $i++) {
            $j = $i + 3;
            //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $i+1);
            $worksheet->setCellValueByColumnAndRow(2, $j, date('Y-m-d',$rows[$i]['createtime']));
            $worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['number']);
            $worksheet->setCellValueByColumnAndRow(4, $j, date('Y-m-d',$rows[$i]['collectiontime']));
            $worksheet->setCellValueByColumnAndRow(5, $j, '销售出库单');
            $worksheet->setCellValueByColumnAndRow(6, $j, $rows[$i]['explain']);
//            $worksheet->setCellValueByColumnAndRow(7, $j, $rows[$i]['abstract']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $rows[$i]['remark']);
            $worksheet->setCellValueByColumnAndRow(8, $j, $rows[$i]['title']);

            if(empty($ccrow)){
                $croww = Db::name('customer')->where(array('id'=>$rows[$i]['customer_id']))->find();
                $worksheet->setCellValueByColumnAndRow(9, $j, $croww['company']);//往来单位
            }else{
                $worksheet->setCellValueByColumnAndRow(9, $j, $ccrow['company']);//往来单位
            }


            $worksheet->setCellValueByColumnAndRow(10, $j, $rows[$i]['operator']);//经手人
            $worksheet->setCellValueByColumnAndRow(11, $j, $rows[$i]['name']);//仓库
            $worksheet->setCellValueByColumnAndRow(12, $j, $rows[$i]['company']);//部门
            $worksheet->setCellValueByColumnAndRow(13, $j, $rows[$i]['specs']);//单位
            $worksheet->setCellValueByColumnAndRow(14, $j, $rows[$i]['goods_num']);//订货数量
            $worksheet->setCellValueByColumnAndRow(15, $j, $rows[$i]['sale_price']*$rows[$i]['goods_num']);//订货金额
            if(isset($rows[$i]['sfhj']) && $rows[$i]['sfhj'] !=0.00){
                $worksheet->setCellValueByColumnAndRow(16, $j, $rows[$i]['sfhj']);//订货合计
                $allprice +=$rows[$i]['sfhj'];
            }else{
                $worksheet->setCellValueByColumnAndRow(16, $j, $rows[$i]['ht_price']*$rows[$i]['goods_num']);//订货合计
                $allprice +=$rows[$i]['ht_price']*$rows[$i]['goods_num'];
            }

            $allnum +=$rows[$i]['goods_num'];
//            $worksheet->setCellValueByColumnAndRow(17, $j, $rows[$i]['tax']);//发货数量
//            $worksheet->setCellValueByColumnAndRow(18, $j, $rows[$i]['tax']);//发货金额
//            $worksheet->setCellValueByColumnAndRow(19, $j, $rows[$i]['tax']);//发货合计
//            $worksheet->setCellValueByColumnAndRow(20, $j, $rows[$i]['tax']);//未发货数量
//            $worksheet->setCellValueByColumnAndRow(21, $j, $rows[$i]['tax']);//未发货金额
//            $worksheet->setCellValueByColumnAndRow(22, $j, $rows[$i]['tax']);//未发货合计
        }
        $worksheet->setCellValueByColumnAndRow(1, $len+3, '合计');
        $worksheet->setCellValueByColumnAndRow(14, $len+3, $allnum);
        $worksheet->setCellValueByColumnAndRow(15, $len+3, $allprice);
        $worksheet->setCellValueByColumnAndRow(16, $len+3, $allprice);
        $filename = '出库单.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');




    }
    public function exportdetail($ids = null){
        $row = Db::name('sales_checkout')
            ->where(array('sc.id'=>$ids))
            ->field('sc.*,c.nickname,s.name')
            ->alias('sc')
            ->join('customer c','sc.customer_id = c.id')
            ->join('storehouse s','sc.storehouse_id = s.id')
            ->find();

        $list = Db::name('sales_checkout_goods')
            ->field('g.id,goods_id,storehouse_id,number,title,place_origin,specs,goods_num,unit,sale_price,ht_price,tax,remark')
            ->alias('g')
            ->where(array('g.sales_checkout_id'=>$ids))
            ->join('goods go','g.goods_id = go.id')
            ->select();

        foreach ($list as $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['buy_price'] = round($v['goods_num']*($v['ht_price']/((100+$v['tax'])/100)),2);
            $list[$k]['tax_all'] = round(($v['ht_price']/($v['tax']+100))*$v['tax']*$v['goods_num'],2);
        }


        $template_path = config('site.file_url').'/template/checkout.xls';
        $spreadsheet = IOFactory::load($template_path);
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
//        $worksheet->setTitle('学生成绩表');

        $len = count($list);
        $rows = $list;

        $worksheet->setCellValueByColumnAndRow(3, 1, $row['nickname']);//供货商
        $worksheet->setCellValueByColumnAndRow(3, 2, $row['operator']);//经手人
        $worksheet->setCellValueByColumnAndRow(3, 3, $row['company']);//部门单位
        $worksheet->setCellValueByColumnAndRow(3, 4, $row['tax']);//税点
        $worksheet->setCellValueByColumnAndRow(3, 5, $row['name']);//入库仓库
        $worksheet->setCellValueByColumnAndRow(3, 6, $row['explain']);//说明
        $worksheet->setCellValueByColumnAndRow(3, 7, $row['address']);//送货地址
        $worksheet->setCellValueByColumnAndRow(3, 8, $row['contacts']);//联系人
        $worksheet->setCellValueByColumnAndRow(3, 9, $row['mobile']);//手机号码
        $worksheet->setCellValueByColumnAndRow(3, 10, $row['mobile']);//运费

        $allnum = 0;
        $price = 0;
        $alltax = 0;
        $allprice = 0;

        for ($i=0; $i < $len; $i++) {
            $j = $i + 13;
            //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $i+1);
            $worksheet->setCellValueByColumnAndRow(2, $j, $rows[$i]['number']);
            $worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['title']);
            $worksheet->setCellValueByColumnAndRow(4, $j, $rows[$i]['place_origin']);
            $worksheet->setCellValueByColumnAndRow(5, $j, $rows[$i]['specs']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $rows[$i]['xstock']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $rows[$i]['stock']);
            $worksheet->setCellValueByColumnAndRow(8, $j, $rows[$i]['goods_num']);
            $worksheet->setCellValueByColumnAndRow(9, $j, $rows[$i]['unit']);
            $worksheet->setCellValueByColumnAndRow(10, $j, $rows[$i]['sale_price']);//
            $worksheet->setCellValueByColumnAndRow(11, $j, $rows[$i]['tax']);//


            $tprice = $rows[$i]['goods_num']*$rows[$i]['ht_price']/(1+$rows[$i]['tax']/100);

            $worksheet->setCellValueByColumnAndRow(12, $j, round($tprice,2));//仓库
            $worksheet->setCellValueByColumnAndRow(13, $j, $rows[$i]['ht_price']);//

            $ttax = $rows[$i]['goods_num']*$rows[$i]['ht_price']/(100+$rows[$i]['tax'])*$rows[$i]['tax'];

            $worksheet->setCellValueByColumnAndRow(14, $j, round($ttax,2));//

            $aprice = $rows[$i]['ht_price']*$rows[$i]['goods_num'];

            $worksheet->setCellValueByColumnAndRow(15, $j,$aprice);//订货金额
            $worksheet->setCellValueByColumnAndRow(16, $j, $rows[$i]['remark']);//订货合计

            $allnum +=$rows[$i]['goods_num'];
            $price += $tprice;
            $alltax += $ttax;
            $allprice += $aprice;
        }
        $worksheet->setCellValueByColumnAndRow(1, $len+13, '合计');
        $worksheet->setCellValueByColumnAndRow(8, $len+13, $allnum);
        $worksheet->setCellValueByColumnAndRow(12, $len+13, round($price,2));
        $worksheet->setCellValueByColumnAndRow(14, $len+13, round($alltax,2));
        $worksheet->setCellValueByColumnAndRow(15, $len+13, $allprice);
        $filename = '出库单.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

    }
    public function printing($ids = null){
        $row = Db::name('sales_checkout')
            ->where(array('sc.id'=>$ids))
            ->field('sc.*,c.company as ccompany,s.name')
            ->alias('sc')
            ->join('customer c','sc.customer_id = c.id')
            ->join('storehouse s','sc.storehouse_id = s.id')
            ->find();

        $list = Db::name('sales_checkout_goods')
            ->field('g.id,goods_id,storehouse_id,go.number,title,place_origin,specs,goods_num,unit,sale_price,ht_price,tax,remark,s.name,sfhj')
            ->alias('g')
            ->where(array('g.sales_checkout_id'=>$ids))
            ->join('goods go','g.goods_id = go.id')
            ->join('supplier_brands s','go.brands_id = s.id','LEFT')
            ->select();

        $srow = Db::name('sales_slip')
            ->where(array('id'=>$row['sales_slip_id']))->find();
        foreach ($list as $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['buy_price'] = round($v['goods_num']*($v['ht_price']/((100+$v['tax'])/100)),2);
            $list[$k]['tax_all'] = round(($v['ht_price']/($v['tax']+100))*$v['tax']*$v['goods_num'],2);
        }
        $this->assign('snick',isset($srow['nickname'])?$srow['nickname']:'');
        $this->assign('hname',isset($hrow['name'])?$hrow['name']:'');
        $this->assign('row',$row);
        $this->assign('srow',$srow);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function cancelbill($ids = null){
        if (!$this->request->isAjax()) {
            $this->error('非法请求');
        }
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        $row = $this->model->find($ids);
        if($row['status'] == 1 || $row['status'] >4){
            $this->error('状态异常');
        }

        $analysis = Db::name('analysis')->where(array(
            'source'=>7,
            'source_id' => $row['id'],
            'storehouse_id' => $row['storehouse_id'],
        ))->find();

        //只有财务数据在待处理的时候 才能处理
        if($analysis['status'] != 1){
            $this->error('财务状态异常,请处理');
        }
        //有费用单的情况
        $costrow = Db::name('cost')->where(array('source_type'=>7,'source_id'=>$ids))->find();
        if(!empty($costrow)){
            if($costrow['status'] <3){
                $this->error('还有待处理的费用单');
            }
        }


        /*
         * 取消财务订单
         * 如果已经出库  回退数据
         *
         */
        Db::startTrans();
        try {
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
            if($row['status'] == 2){
                $this->model->save(array('status' => 6), array('id' => $ids));

                //所有商品设置无效
                $checkoutgoods = new CheckoutGoods();
                $checkoutgoods->save(array('status'=>0),array('sales_checkout_id'=>$ids));

//                $srow = Slip::where(array('id'=>$row['sales_slip_id']))->find();
//                if($srow['status'] == 4){//退回状态
//                    Slip::where(array('id'=>$row['sales_slip_id']))->update(array('status'=>3));
//                }
                //检查销售单下是否还有出库单
                $count = Db::name('sales_checkout')->where(array('status'=>array('<',4),'sales_slip_id'=>$row['sales_slip_id']))->count();

                if($count >0){
                    $slip = new Slip();
                    $slip->save(array('status'=>3),array('id'=>$row['sales_slip_id']));
                    $state = 2;
                }else{
                    $slip = new Slip();
                    $slip->save(array('status'=>2),array('id'=>$row['sales_slip_id']));
                    $state = 1;
                }
                    //销售单商品状态
                Db::name('sales_goods')->where(array('sales_slip_id' => $row['sales_slip_id'],'status'=>array('neq',6)))->update(array('status' => $state));

            }
            if($row['status'] == 3 || $row['status'] == 4){

                //如果已经出库 需要检查是否退换货
                if($row['status'] == 4){
                    $Change = new Change;
                    $count1 = $Change->where(array('sales_checkout_id'=>$ids,'status'=>array('<',7)))->count();
                    $Retreat = new Retreat();
                    $count2 = $Retreat->where(array('sales_checkout_id'=>$ids,'status'=>array('<',4)))->count();
                    if($count1>0){
                        throw new Exception('还有换货单没处理');
                    }
                    if($count2>0){
                        throw new Exception('还有退货单没处理');
                    }
                }
                $plist = Db::name('sales_checkout_goods')->where(array('sales_checkout_id'=>$ids))->select();

                //出库单作废
                $this->model->save(array('status' => 6), array('id' => $ids));
                //所有商品设置无效
                Db::name('sales_checkout_goods')->where(array('sales_checkout_id'=>$ids))->update(array('status'=>0));

                //检查销售单下是否还有出库单
                $count = Db::name('sales_checkout')->where(array('status'=>array('<',5),'sales_slip_id'=>$row['sales_slip_id']))->count();

                if($count >0){
                    $slip = new Slip();
                    $slip->save(array('status'=>3),array('id'=>$row['sales_slip_id']));
                    $state = 2;
                }else{
                    $slip = new Slip();
                    $slip->save(array('status'=>2),array('id'=>$row['sales_slip_id']));
                    $state = 1;
                    Db::name('sales_goods')->where(array('sales_slip_id' => $row['sales_slip_id'],'status'=>array('neq',6)))->update(array('status' => $state));
                }

                $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();



                foreach ($plist as $k=>$v){
                    //销售单商品状态
                    if($state == 2){
                        Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>$state));
                    }


                    //增加库存
                    $GoodsHouseStock = new GoodsHouseStock;
                    $rr = $GoodsHouseStock->addstock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],$v['costPrice'],1);
                    if(!$rr){
                        throw new Exception('库存异常');
                    }

                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();


                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'销售出库单',
                        'source'=>7,
                        'type_id'=>$row['id'],
//                       'enter_num'=>$v['goods_num'],
                        'enter_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock']-$v['goods_num'],
                        'now_num'=>$hgood['stock'],
                        'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                        'controller'=>'sales/checkout',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'final_cost'=>$v['costPrice'], //记录的金额应该是出库的加权单价
                        'bill_cost'=>$v['costPrice']*$v['goods_num'], //记录的金额应该是入库的采购成本
                        'balance'=>$hgood['balance'], //记录的金额当前库存总额
                        'is_cancel'=>1,
                    ));
                }
            }


            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 7,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'sales/checkout',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));

            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'sales/checkout',
                'source_id'=>$ids,
                'source'=>7,
                'remark'=>'销售出库单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));


            //财务单据作废
            $ress = Db::name('analysis')->where(array(
                'id' => $analysis['id']
            ))->update(array('status' => 4));
            if (!$ress) {
                throw new Exception('数据异常');
            }


            Db::commit();
            return array(
                'code' => 1,
                'msg' => '成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
//        if($row['status'] == 2){
//            $this->endcheckout($ids);
//        }

    }
    public function getcount()
    {
        $filter = input('');
        $where=[];
        $where['ss.status'] = array('<',5);
        if(session('admin')['storehouse_id'] >0){
            $where['ss.storehouse_id'] = session('admin')['storehouse_id'];
        }

        if(!empty($filter)){
            foreach ($filter as $key =>$value){
                if($key == 'number' && !empty($value)){
                    $where['ss.number'] = array('like','%'.$value.'%');
                }
                if($key == 'slip_number' && !empty($value)){
                    $where['ss.number'] = array('like','%'.$value.'%');
                }
                if($key == 'operator' && !empty($value)){
                    $where['ss.operator'] = array('like','%'.$value.'%');
                }
                if($key == 'company' && !empty($value)){
                    $where['ss.company'] = array('like','%'.$value.'%');
                }
                if($key == 'id' && !empty($value)){
                    $where['ss.id'] = $value;
                }
                if($key == 'status' && !empty($value)){
                    $where['ss.status'] = $value;
                }
                if($key == 'storehouse_name' && !empty($value)){//仓库
                    $where2['name'] = $value;
                    $info = Storehouse::where($where2)->find();
                    $where['ss.storehouse_id'] = $info['id'];
                }
                if($key == 'customer_nickname' && !empty($value) && !empty($value)){
                    $where1['nickname'] = array('like','%'.$value.'%');
                    $list =  Customer::where($where1)->field('id')->select();

                    if(!empty($list)){
                        foreach ($list as $v){
                            $ids[] = $v['id'];
                        }
                        $where['ss.customer_id'] = array('in',$ids);
                    }
                }
                if($key == 'createtime' && !empty($value)){
                    $arr = explode(' - ', $value);
                    $where['ss.createtime'] = array('between time',$arr);
                }
            }
        }

        $num = Db::name('sales_checkout')
            ->alias('ss')
            ->where($where)
            ->join('customer c','ss.customer_id = c.id')
            ->join('storehouse h','ss.storehouse_id = h.id')
            ->sum('checkout_num');
        $price = Db::name('sales_checkout')
            ->alias('ss')
            ->where($where)
            ->join('customer c','ss.customer_id = c.id')
            ->join('storehouse h','ss.storehouse_id = h.id')
            ->sum('actual_cost');

        $result = array('num'=>$num,'price'=>$price);

        return json($result);
    }

    public function gather(){
        return $this->view->fetch();
    }
    public function gatherres(){
        $params = input();
        $start_time = input('starttime');
        $end_time = input('endtime');
        $number = input('number');
        $type = input('type/d',1);


        if ($this->request->isAjax()) {
            $start_time = 0;
            $end_time = time();
            $filter = json_decode(input('filter'),true);


            $where = [];
            $where1 = '';

            if(!empty($filter)){
                foreach ($filter as $k => $v){
                    if($k == 'customer_id' && !empty($v)){
                        $crow = Db::name('customer')->where(array('id' => $v))->find();
                        $where['customer_id'] = isset($crow['id'])?$crow['id']:0;
                    }
                    if($k == 'number' && !empty($v)){
                        $grow = Db::name('goods')->where(array('number' =>$v))->find();
                        $where['goods_id']=isset($grow['id'])?$grow['id']:0;
                    }
                    if($k == 'goods_id' && !empty($v)){
                        $where['goods_id']=$v;
                    }
                    if($k == 'storehouse_id' && !empty($v)){
                        $where['storehouse_id']=$v;
                    }
                    if($k == 'start_time' && !empty($v)){
                        $start_time = strtotime($v);
                    }
                    if($k == 'end_time' && !empty($v)){
                        $end_time = strtotime($v);
                    }
                    if($k == 'type' && !empty($v)){
                       $type = $v;
                    }
                }
            }
//            dump($where);
            if(empty($where)){
                $where1 = 'createtime BETWEEN ' . $start_time . ' AND ' . $end_time . '';
            }else{
                foreach ($where as $k => $v){
                    if(empty($where1)){
                        $where1 .=''.$k.' ='.$v.'';
                    }else{
                        $where1 .=' AND '.$k.' ='.$v.'';
                    }

                }
                $where1 .= ' AND createtime BETWEEN ' . $start_time . ' AND ' . $end_time . '';

            }
            $where1 .=' AND status > 0';
            $where['createtime'] = array('between time', [$start_time, $end_time]);
//            dump($where);
//            dump($where1);
            $where['status'] = array('>',0);
            $page = input('offset/d',0);
            $pagesize = input('limit/d',0);

//            SELECT * FROM `zax_factory_sales` `f` INNER JOIN `zax_factory_sales_goods` `g` ON `f`.`id`=`g`.`factory_sales_id`


            switch ($type){
                case 1:
                    $field1 = 'id,goods_id,createtime,factory_sales_id,sale_type,sfhj,ht_price,sale_price,goods_num,customer_id';
                    $field = 'id,goods_id,createtime,sales_slip_id,sale_type,sfhj,ht_price,sale_price,goods_num,customer_id';
                    $list =Db::field($field)
                        ->table('zax_sales_checkout_goods')
                        ->union('SELECT ' . $field1 . ' FROM zax_factory_sales_goods where '.$where1.'', true)
                        ->limit($page,$pagesize)
                        ->where($where)
                        ->order('createtime', 'DESC')
                        ->select();
                    break;
                case 2://销售单
                    $field = 'id,goods_id,createtime,sales_slip_id,sale_type,sfhj,ht_price,sale_price,goods_num,customer_id';
                    $list = Db::name('sales_checkout_goods')
                        ->field($field)
                        ->limit($page,$pagesize)
                        ->where($where)
                        ->order('createtime', 'DESC')
                        ->select();
                    break;
                case 3:
                    $field = 'id,goods_id,createtime,factory_sales_id as sales_slip_id,sale_type,sfhj,ht_price,sale_price,goods_num,customer_id';
                    $list = Db::name('factory_sales_goods')
                        ->field($field)
                        ->limit($page,$pagesize)
                        ->where($where)
                        ->order('createtime', 'DESC')
                        ->select();
                    break;
                default:
                    return array(
                      'list'=>[],
                      'total'=>0
                    );
                    break;
            }


            $goods_ids = [];
            $factory_ids = [];
            $sales_ids = [];
            $customer_ids = [];
            foreach ($list as $k=> $v){
                $goods_ids[] = $v['goods_id'];
                $customer_ids[] = $v['customer_id'];
                if(empty($v['sale_type'])){
                    $factory_ids[] = $v['sales_slip_id'];
                }
                if(!empty($v['sale_type'])){
                    $sales_ids[] = $v['sales_slip_id'];
                }
            }
            $frows = Db::name('factory_sales')->where(array('id'=>array('in',$factory_ids)))->select();
            $srows = Db::name('sales_slip')->where(array('id'=>array('in',$sales_ids)))->select();
            $goods = Db::name('goods')->where(['id'=>array('in',$goods_ids)])->select();
            $crows = Db::name('customer')->where(['id'=>array('in',$customer_ids)])->select();
            foreach ($list as &$v){
                foreach ($frows as $val){
                    if(empty($v['sale_type']) && $v['sales_slip_id'] == $val['id']){
                        $v['number'] = $val['number'];
                        $v['operator'] = $val['operator'];
                        $v['company'] = $val['company'];
                        $v['type'] = '厂家直发单';
                    }
                }
                foreach ($srows as $val){
                    if(!empty($v['sale_type']) && $v['sales_slip_id'] == $val['id']){
                        $v['number'] = $val['number'];
                        $v['operator'] = $val['operator'];
                        $v['company'] = $val['company'];
                        $v['type'] = '销售出库单';
                    }
                }
                foreach ($goods as $val){
                    if($val['id'] == $v['goods_id']){
                        $v['title'] = $val['title'];
                    }
                }
                foreach ($crows as $val){
                    if($val['id'] == $v['customer_id']){
                        $v['nickname'] = $val['nickname'];
                    }
                }
            }
//            dump($list);


            $total1 =Db::table('zax_sales_checkout_goods')
//                ->union('SELECT ' . $field1 . ' FROM zax_factory_sales_goods where '.$where1.'', true)
//                ->page($page,$pagesize)
                ->where($where)
                ->count();
            $total2 = Db::table('zax_factory_sales_goods')->where($where)->count();

            return  array(
                'rows'=>$list,
                'total'=>$total1+$total2,
            );
        }

        if (isset($params['customer_id']) && !empty($params['customer_id'])) {
            $crow = Db::name('customer')->where(array('nickname' => $params['customer_id']))->find();
            if ($crow) {
                $customer_id = $crow['id'];
            }else{
                $customer_id = 0;
            }
        }else{
            $customer_id = 0;
        }
        $storehouse_id = input('storehouse_id/d',0);
        $this->assign('customer_id',$customer_id);
        $this->assign('type',$type);
        $this->assign('storehouse_id',$storehouse_id);
        $this->assign('start_time',$start_time);
        $this->assign('end_time',$end_time);
        $this->assign('number',$number);
        return $this->view->fetch();
    }
}
